<template>
  <div class="edit_box">
    <el-scrollbar>
      <el-form
        ref="Form"
        class="Form"
        :model="pageData.formData"
        :rules="pageData.formRules"
        status-icon
        label-width="100px"
      >
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="单别：" prop="fOrderCategory">
              <!-- <el-input
                v-model="pageData.formData.fOrderCategory"
                :disabled="!pageData.isAdd || pageData.isAdd"
              /> -->
              <span>{{ pageData.formData.fOrderCategory }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单号：" prop="fOrderNumber">
              <!-- <el-input
                v-model="pageData.formData.fOrderNumber"
                :disabled="!pageData.isAdd || pageData.isAdd"
              /> -->
              <span>{{ pageData.formData.fOrderNumber }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态：" prop="fState">
              <!-- <el-input
                v-model="pageData.formData.fState"
                :disabled="!pageData.isAdd || pageData.isAdd"
              /> -->
              <span>{{ pageData.formData.fState }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单据日期：" prop="fOrderTime">
              <!-- <el-input
                v-model="pageData.formData.fOrderTime"
                :disabled="!pageData.isAdd || pageData.isAdd"
              /> -->
              <span>{{ pageData.formData.fOrderTime }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单位：" prop="fOrgId">
              <!-- <el-input
                v-model="pageData.formData.fOrgId"
                :disabled="!pageData.isAdd || pageData.isAdd"
              /> -->
              <span>{{ pageData.formData.fOrgId }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="人员：" prop="fFullName">
              <!-- <el-input
                v-model="pageData.formData.fFullName"
                :disabled="!pageData.isAdd || pageData.isAdd"
              /> -->
              <span>{{ pageData.formData.fFullName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注：">
              <!-- <el-input
                v-model="pageData.formData.fRemark"
                autocomplete="off"
                :disabled="!pageData.isAdd || pageData.isAdd"
              /> -->
              <span>{{ pageData.formData.fRemark }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 子表 -->
        <el-row>
          <!-- <el-button type="primary" @click="onHandleEquipAdd">
            <el-icon><Plus /></el-icon>
            <span>新增</span>
          </el-button> -->
          <el-table
            style="width: 100%; margin: 10px 0; height: 400px"
            border
            :data="pageData.formData.retireDemandDtls"
          >
            <el-table-column
              fixed
              prop="fName"
              min-width="120"
              label="名称"
              align="center"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              prop="fSpec"
              min-width="120"
              label="规格"
              align="center"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              prop="fFromNumber"
              min-width="160"
              label="来源单号"
              align="center"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              prop="fRetireOrgName"
              min-width="120"
              label="退役单位"
              align="center"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              prop="fUnit"
              min-width="120"
              label="计数单位"
              align="center"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              prop="fNumber"
              min-width="120"
              label="本次计划数量"
              align="center"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              prop="fQualityGrade"
              min-width="120"
              label="质量等级"
              align="center"
              :show-overflow-tooltip="true"
            />
            <!-- <el-table-column prop="fParamCode" label="编号">
              <template #default="{ row }">
                <el-input v-model="row.fParamCode" readonly>
                  <template #suffix>
                    <el-icon
                      style="cursor: pointer"
                      @click="onSelectParam(row)"
                    >
                      <ArrowDown />
                    </el-icon>
                  </template>
                </el-input> </template
            ></el-table-column> -->
            <!-- <el-table-column prop="fCode" label="编号" min-width="120px" fixed>
              <template #default="{ row }">
                <el-input v-model="row.fCode" />
              </template>
            </el-table-column> -->
            <!-- <el-table-column prop="fName" label="名称" min-width="120px">
              <template #default="{ row }">
                <el-input v-model="row.fName" />
              </template>
            </el-table-column>
            <el-table-column prop="fSpec" label="规格" min-width="120px">
              <template #default="{ row }">
                <el-input v-model="row.fSpec" />
              </template>
            </el-table-column>
            <el-table-column prop="fUnit" label="逐批/逐号" min-width="120px">
              <template #default="{ row }">
                <el-input v-model="row.fUnit" />
              </template>
            </el-table-column>
            <el-table-column prop="fUnit" label="来源单号" min-width="120px">
              <template #default="{ row }">
                <el-input v-model="row.fUnit" />
              </template>
            </el-table-column>
            <el-table-column prop="fUnit" label="计数单位" min-width="120px">
              <template #default="{ row }">
                <el-input v-model="row.fUnit" />
              </template>
            </el-table-column>
            <el-table-column prop="fUnit" label="数量" min-width="120px">
              <template #default="{ row }">
                <el-input v-model="row.fUnit" />
              </template>
            </el-table-column>
            <el-table-column prop="fUnit" label="质量等级" min-width="120px">
              <template #default="{ row }">
                <el-input v-model="row.fUnit" />
              </template>
            </el-table-column>
            <el-table-column prop="fUnit" label="备注" min-width="120px">
              <template #default="{ row }">
                <el-input v-model="row.fUnit" />
              </template>
            </el-table-column> -->
            <!-- <el-table-column
              prop="fRequiredNumber"
              label="需求数量"
              min-width="145"
            >
              <template #default="{ row }">
                <el-input-number
                  v-model="row.fRequiredNumber"
                  :min="0"
                  :max="10000000"
                  size="small"
                />
              </template>
            </el-table-column> -->
            <!-- <el-table-column
              prop="fPlannedNumber"
              label="计划数量"
              min-width="145"
            >
              <template #default="{ row }">
                <el-input-number
                  v-model="row.fPlannedNumber"
                  :min="0"
                  :max="10000000"
                  size="small"
                />
              </template>
            </el-table-column> -->
            <!-- <el-table-column
              prop="fRetiredNumber"
              label="退役数量"
              min-width="145"
            >
              <template #default="{ row }">
                <el-input-number
                  v-model="row.fRetiredNumber"
                  :min="0"
                  :max="10000000"
                  size="small"
                />
              </template>
            </el-table-column> -->
            <!-- <el-table-column
              prop="fDestroyedNumber"
              label="销毁数量"
              min-width="145"
            >
              <template #default="{ row }">
                <el-input-number
                  v-model="row.fDestroyedNumber"
                  :min="0"
                  :max="10000000"
                  size="small"
                />
              </template>
            </el-table-column> -->
            <!-- <el-table-column label="操作" width="60" fixed="right">
              <template #default="{ row }">
                <el-icon
                  title="删除"
                  style="cursor: pointer; margin: 0 3px"
                  @click="onHandleEquipDel(row)"
                >
                  <Delete />
                </el-icon>
              </template>
            </el-table-column> -->
          </el-table>
        </el-row>
      </el-form>
    </el-scrollbar>
    <el-row class="btns">
      <el-col :span="24" style="text-align: right">
        <el-button v-if="pageData.isShowsubmit" @click="dataSubmit"
          >提交</el-button
        >
        <el-button
          v-if="pageData.isShowAudit"
          @click="pageData.dialogAuditVisible = true"
          >审核</el-button
        >
        <el-button @click="shHis">审核历史</el-button>

        <el-button v-if="pageData.isShowUndo" @click="dataUndo"
          >单步撤回</el-button
        >
        <el-button v-if="pageData.isShowCancel" @click="dataCancel"
          >作废</el-button
        >
        <el-button @click="onHandleCancel">取消</el-button>

        <!-- <el-button type="primary" @click="onHandleSure"> 保存 </el-button> -->
      </el-col>
    </el-row>
    <!-- 审核弹窗 -->
    <el-dialog v-model="pageData.dialogAuditVisible" title="审核">
      <el-form :model="form">
        <el-form-item label="审核意见" :label-width="formLabelWidth">
          <el-input v-model="pageData.submit.opinion" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="auditCel">不通过</el-button>
          <el-button type="primary" @click="auditOk"> 通过 </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 审核历史 -->
    <el-dialog
      v-model="popUpShow.hisOrder"
      title="审核历史"
      width="50%"
      heigth="16%"
      draggable
    >
      <hisTotis :list="popUpShow.hisList"></hisTotis>
    </el-dialog>
  </div>
</template>

<script>
import { onMounted, reactive, ref, watch } from "vue";
import { ElLoading, ElMessage, ElMessageBox } from "element-plus";
import { Plus, Delete, ArrowDown } from "@element-plus/icons-vue";
import hisTotis from "@/components/hisTotis/hisTotis.vue";

import { departmentList } from "@/api/GeneralList/departmentList";
import {
  retireBill_details,
  submit,
  audit,
  cancelretireBill,
  history,
  undo,
} from "@/api/Retirement/RetirementBill";
import { getHisTo } from "@/api/login/login.js";

export default {
  components: { Plus, Delete, ArrowDown, hisTotis },

  props: {
    modifyObj: { type: Object, required: true },
    isAdd: { type: Boolean, required: true, default: false },
  },
  setup(props, context) {
    onMounted(() => {
      if (!props.isAdd) {
        getData(props.modifyObj);
      }
    });

    // 表单绑定返回的数据
    const Form = ref();

    let pageData = reactive({
      Fid: "",
      // 按钮的显示隐藏
      isShowsubmit: false,
      isShowAudit: false,
      isShowUndo: false,
      isShowCancel: false,
      formData: {
        retireDemandDtls: [],
      },
      formRules: {
        // fOrgName: [{ required: true, message: "请选择单位" }],
        // fOrderCategory: [
        //   { required: true, message: "请选择单别", trigger: "blur" },
        // ],
        // fFromNumber: [
        //   { required: true, message: "请输入来源号", trigger: "blur" },
        // ],
        // fOrderCategory: [
        //   { required: true, message: "请选择单别", trigger: "blur" },
        // ],
        // fRetireTime: [
        //   { required: true, message: "请选择退役日期", trigger: "blur" },
        // ],
      },
      // 树
      treeData: [],
      treeParams: {
        props: {
          label: "fh",
          children: "orgDirectoryVos",
          isLeaf: function (data, node) {
            if (data.isleaf == 2) {
              return true;
            } else {
              return false;
            }
          },
        },
        defaultExpKeys: [],
        currentNode: {},
        defaultTree: [],
      },

      isAdd: props.isAdd,
      currentRow: {},

      // 提交
      submit: {
        billId: "",
        billType: 0,
        freeNextUnitIndex: 0,
        freeNextUser: "",
        tokenDto: {
          fclienttype: "",
          ffullname: "",
          fgrouporgid: "",
          fgrouporgnm: "",
          fisdealer: 0,
          fpersonid: "",
          fuserid: "",
          fusername: "",
        },
        opinion: "", //审核意见
        pass: "", //是否通过
      },
      // 入库单作废和回退
      dataCancel: {
        billType: 1,
        billId: "",
      },
    });
    // 查询详情
    const getData = (item) => {
      console.log("item", item);
      if (item.billName) {
        pageData.Fid = item.entityId;
        console.log("entityId", pageData.Fid);
        pageData.submit.billId = item.entityId;
        pageData.dataCancel.billId = item.entityId;
      } else {
        pageData.Fid = item.fId;
        console.log("item.fId", item.fId);
        pageData.submit.billId = item.fId;
        pageData.dataCancel.billId = item.fId;
      }
      retireBill_details(pageData.Fid)
        .then((res) => {
          console.log("查询详情", res);
          pageData.formData = res;
          pageData.formData.retireDemandDtls = res.retirePlanDtlVos;

          if (res.fState == 0) {
            pageData.isShowsubmit = true;
            pageData.isShowCancel = true;
          } else if (res.fState == 10) {
            pageData.isShowAudit = true;
            pageData.isShowUndo = true;
            pageData.isShowCancel = true;
          } else if (res.fState == 30) {
            pageData.isShowsubmit = false;
            pageData.isShowAudit = false;
            pageData.isShowUndo = false;
            pageData.isShowCancel = false;
          }
        })
        .catch((error) => {
          ElMessage.error(error);
        });
    };

    // 提交
    const dataSubmit = () => {
      submit(pageData.submit)
        .then((res) => {
          console.log("提交", res);
          ElMessage({
            type: "success",
            message: "提交成功",
          });
          context.emit("ok", {
            isAdd: props.isAdd,
          });
        })
        .catch((error) => {
          console.log(error);
          ElMessage.error(error.message || "请求出错");
        });
    };

    /* 审核历史 */
    let popUpShow = reactive({
      hisOrder: false,
      hisList: [],
    });
    // 审核历史
    const shHis = () => {
      history(pageData.submit)
        .then((res) => {
          console.log("审核历史", res);
          let arr = res.map((item, index) => {
            return {
              content: `${item.notifyTime} ${item.unitIndex} ${
                item.assignUser
              } ${item.isReject ? "【已驳回】" : "【已通过】"} 审核时间:${
                item.completeTime
              }`,
              timestamp: item.opinion,
              type: item.isReject ? -1 : 1,
            };
          });
          if (!arr[arr.length - 1].isReject) {
            arr[arr.length - 1].isReject = true;
            arr[arr.length - 1].content = arr[arr.length - 1].content
              .split("已驳回")
              .join("待处理");
          }
          popUpShow.hisOrder = true;
          popUpShow.hisList = arr;
        })
        .catch((error) => {
          ElMessage.error(error.message || "请求出错");
        });
      // getHisTo(props.modifyObj.entityId || props.modifyObj.fId, "/retire/bill")
      //   .then((res) => {
      //     console.log(res);
      //     let arr = res.map((item, index) => {
      //       return {
      //         content: `${item.notifyTime} ${item.unitIndex} ${
      //           item.assignUser
      //         } ${item.isReject ? "【已驳回】" : "【已通过】"} 审核时间:${
      //           item.completeTime
      //         }`,
      //         timestamp: item.opinion,
      //         type: item.isReject ? -1 : 1,
      //       };
      //     });
      //     if (!arr[arr.length - 1].isReject) {
      //       arr[arr.length - 1].isReject = true;
      //       arr[arr.length - 1].content = arr[arr.length - 1].content
      //         .split("已驳回")
      //         .join("待处理");
      //     }
      //     popUpShow.hisList = arr;
      //     popUpShow.hisOrder = true;
      //   })
      //   .catch((err) => {
      //     ElMessage.error("服务器异常");
      //   });
    };

    // 审核
    const auditCel = () => {
      pageData.dialogAuditVisible = false;
      pageData.submit.pass = false;
      audit(pageData.submit)
        .then((res) => {
          console.log("审核", res);
          ElMessage({
            type: "success",
            message: "操作成功",
          });
          context.emit("ok", {
            isAdd: props.isAdd,
          });
        })
        .catch((error) => {
          ElMessage.error(error.message || "请求出错");
        });
      pageData.submit.opinion = "";
    };
    const auditOk = () => {
      pageData.dialogAuditVisible = false;
      pageData.submit.pass = true;
      audit(pageData.submit)
        .then((res) => {
          console.log("审核", res);
          ElMessage({
            type: "success",
            message: "审核成功",
          });
          context.emit("ok", {
            isAdd: props.isAdd,
          });
        })
        .catch((error) => {
          ElMessage.error(error.message || "请求出错");
        });
      pageData.submit.opinion = "";
    };
    // 回退
    const dataUndo = () => {
      undo(pageData.dataCancel)
        .then((res) => {
          console.log("回退", res);
          ElMessage({
            type: "success",
            message: "回退成功",
          });
          context.emit("ok", {
            isAdd: props.isAdd,
          });
        })
        .catch((error) => {
          ElMessage.error(error.message || "请求出错");
        });
    };
    // 作废
    const dataCancel = () => {
      cancelretireBill(pageData.dataCancel)
        .then((res) => {
          console.log("作废", res);
          ElMessage({
            type: "success",
            message: "操作成功",
          });
          context.emit("ok", {
            isAdd: props.isAdd,
          });
        })
        .catch((error) => {
          ElMessage.error(error.message || "请求出错");
        });
    };
    // 取消
    const onHandleCancel = () => {
      Form.value?.resetFields();
      context.emit("cancel");
    };

    return {
      Form,
      pageData,

      shHis,
      dataSubmit,
      auditCel,
      auditOk,
      dataUndo,
      dataCancel,
      popUpShow,
      getData,
      onHandleCancel,
      // onHandleSure,
    };
  },
};
</script>

<style lang="scss" scoped>
.edit_box {
  height: 100%;
  background-color: white;
  .Form {
    width: calc(100% - 6px);
  }

  .el-scrollbar {
    height: 83%;
  }
  .btns {
    margin-top: 20px;
  }
}
</style>
